<template>
  <div class="setNoticeBox">
    <el-card v-loading="isAjaxing" row-key="id">
      <div style="margin-bottom: 20px">
        <el-button size="mini" @click="getNoticeFun"><i class="el-icon-refresh-right"></i></el-button>
        <el-button type="primary" size="mini" @click="dialogShow=true;dialogTitle='添加公告'"><i class="el-icon-plus"></i> 新增</el-button>
        <el-button type="danger" size="mini" @click="deleteConfirm(selectKeys)"><i class="el-icon-delete"></i> 删除选中</el-button>
      </div>
      <el-table :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="ID" prop="id" width="80"></el-table-column>
        <el-table-column label="标题" prop="title"></el-table-column>
        <el-table-column label="是否为草稿" prop="state">
          <template #default="{ row }">
            <el-switch :loading="row.stateLoading" :before-change="()=>switchChange(row,'state')" v-model="row.state" :active-value="1" :inactive-value="0"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="置顶" prop="main">
          <template #default="{ row }">
            <el-switch :loading="row.mainLoading" :before-change="()=>switchChange(row,'main')" v-model="row.main" :active-value="1" :inactive-value="0"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" prop="create_time" width="200"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="mini" type="primary" @click="editShow(row)"><i class="el-icon-edit"></i></el-button>
            <el-button size="mini" type="danger" @click="deleteConfirm([row.id])"><i class="el-icon-delete"></i></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="filter.page"
          :page-sizes="[10, 50, 100, 150]"
          :page-size="filter.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog v-model="dialogShow" :title="dialogTitle" @opened="dialogOpend" :before-close="beforeClose">
      <el-form label-position="top" :model="dialogForm" :rules="formRules" ref="formRef">
        <el-form-item label="标题" prop="title">
          <el-input placeholder="请输入标题" v-model="dialogForm.title"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <div id="textArea"></div>
        </el-form-item>
<!--        <el-form-item label="添加时间">-->
<!--          <el-input placeholder="如 2021-12-12 10:10:10"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="置顶" prop="main">
          <el-switch v-model="dialogForm.main" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="保存为草稿" prop="state">
          <el-switch v-model="dialogForm.state" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogShow = false" size="mini" type="default">取消</el-button>
        <el-button @click="onSubmit" :loading="isSubmit" size="mini" type="primary">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, toRefs } from 'vue'
import { addNotice, deleteNotices, editNotice, getNotice, upload } from '../../../axios/adminRequest'
import E from 'wangeditor'
import { computedPage } from '../../../utils/utils'
import baseUrl from '../../../axios/baseUrl'
export default {
  name: 'setNotice',
  setup(){
    let { proxy } = getCurrentInstance()
    const state = reactive({
      isAjaxing:true,
      isSubmit:false,
      filter:{
        page:1,
        limit:10
      },
      total:0,
      tableData:[],
      selectKeys:[],
      dialogShow:false,
      dialogTitle:'添加公告',
      editId:'',
      dialogForm:{
        title:'',
        state:0,
        main:0,
        content:''
      },
      formRules:{
        title: [{ required:true,message:'请输入公告标题',trigger:'blur' }],
        content: [{ required:true,message:'请输入公告内容',trigger:'blur' }],
        main:[],
        state:[]
      }
    })
    let editor = null

    const uploadFile = (resultFiles, insertImgFn)=>{
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      let param = new FormData()  // 创建form对象
      param.append('file', resultFiles[0])
      param.append('path', 'notice')
      upload(param).then(res=>{
        if(res.code == 0){
          // 上传图片，返回结果，将图片插入到编辑器中
          insertImgFn(baseUrl +'/'+res.data.path)
        }
      })
    }

    const createEditor = () => {

    }

    const dialogOpend = ()=>{
      if(!editor) {
        editor = new E('#textArea')
        editor.config.customUploadImg = uploadFile
        editor.config.customUploadVideo = uploadFile
        editor.create()
        if(state.dialogTitle.indexOf('修改') >= 0){
          state.tableData.forEach(item=>{
            if(item.id == state.editId){
              editor.txt.html(item.content)
            }
          })
        }
      }
    }

    const getNoticeFun = () => {
      state.isAjaxing = true
      getNotice(state.filter).then(data=>{
        if(data.code == 0){
          state.filter.page = data.data.current_page
          state.total = data.data.total
          state.tableData = data.data.data
        }else{
          proxy.$message.error(data.msg)
        }
        state.isAjaxing = false
      })
    }
    getNoticeFun()

    const handleSizeChange = (pageSize)=>{
      state.filter.page = 1
      state.filter.limit = pageSize
      getNoticeFun()
    }

    const handleCurrentChange = (page)=>{
      state.filter.page = page
      getNoticeFun()
    }

    const deleteConfirm = (list) => {
      proxy.$confirm('确认要删除公告吗？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type:'error'
      }).then(()=>{
        state.isAjaxing = true
        deleteNotices({id:list}).then(data=>{
          if(data.code == 0){
            proxy.$message.success('删除成功')
            state.filter.page = computedPage(list.length,state.filter.page,state.filter.limit,state.total)
            getNoticeFun()
          }else{
            proxy.$message.error(data.msg)
            state.isAjaxing = false
          }
        })
      })
    }

    const resetForm = () => {
      proxy.$refs.formRef.resetFields()
      editor.txt.html('')
    }

    const onSubmit = () => {
      state.dialogForm.content = editor.txt.html()
      proxy.$refs.formRef.validate(bool=>{
        if(bool){
          state.isSubmit = true
          let result;
          if(state.dialogTitle == '添加公告'){
            result = addNotice(state.dialogForm)
          }else{
            result = editNotice(state.editId,state.dialogForm)
          }
          result.then(res=>{
            if(res.code == 0){
              resetForm()
              proxy.$message.success('操作成功')
              state.dialogShow = false
              getNoticeFun()
            }else{
              proxy.$message.error(res.msg)
            }
            state.isSubmit = false
          })
        }
      })
    }

    const beforeClose = (done) => {
      if(state.isSubmit){
        proxy.$message.warning('暂时无法关闭')
      }else{
        resetForm()
        done()
      }
    }

    const editShow = (row) => {
      state.dialogTitle ='修改公告';
      state.editId = row.id
      state.dialogForm.title = row.title
      state.dialogForm.main = row.main
      state.dialogForm.state = row.state
      state.dialogShow = true;
      if(editor){
        editor.txt.html(row.content)
      }
    }

    const handleSelectionChange = (val)=>{
      let arr = []
      val.forEach(item=>{
        arr.push(item.id)
      })
      state.selectKeys = arr;
    }

    const switchChange = (row,type) => {
      return new Promise((resolve, reject)=>{
        let form = {}
        if(type=='main'){
          form.main = row.main == 0 ? 1 : 0
        }else{
          form.state = row.state == 0 ? 1 : 0

        }
        row[`${type}Loading`] = true
        editNotice(row.id,form).then(res=>{
          if(res.code == 0){
            resolve(true)
          }else {
            proxy.$message.error(res.msg)
            reject()
          }
          row[`${type}Loading`] = false
        })
      })
    }

    return {
      ...toRefs(state),
      getNoticeFun,
      handleSizeChange,
      handleCurrentChange,
      deleteConfirm,
      dialogOpend,
      onSubmit,
      beforeClose,
      editShow,
      handleSelectionChange,
      switchChange
    }
  }
}
</script>

<style lang="less" scoped>
.setNoticeBox{
  .el-table{
    &:deep(.el-table__row){
      .cell{
        font-size: 12px;
      }
    }
  }
  &:deep(.el-dialog){
    max-width: 900px !important;
  }
}
</style>
